package com.android.fastride.present;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.android.fastride.Constant;
import com.android.fastride.activity.ProxyFragmentActivity;
import com.android.fastride.contract.CompletedOrderListContract;
import com.android.fastride.model.db.entity.Order;
import com.android.fastride.model.db.entity.OrderResponse;
import com.android.fastride.model.repository.ControlSystemRepository;
import com.android.fastride.view.fragment.OrderDetailFragment;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.peng.android.coremodule.utils.RxSchedulerUtils;
import com.peng.library.mantis.expand.list.MantisListPresent;
import com.peng.library.mantis.mvp.PresentEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class CompletedOrderListPresent extends MantisListPresent<CompletedOrderListContract.VIEW, Order>
        implements CompletedOrderListContract.PRESENT {
    public static final String TAG = "CompletedOrderListPresent";
    private int mRow = 10;
    private int mPage = 1;
    private boolean isRefreshCall = false;
    private boolean isHasNextPage = false;
    int type;
    private List<Order> testDataList = new ArrayList<>(15);

    @Override
    public void onCreate(CompletedOrderListContract.VIEW view, Bundle data) {
        super.onCreate(view, data);
    }

    @Override
    public void onCreateView(CompletedOrderListContract.VIEW view) {
        super.onCreateView(view);
       type = getView().getOrderStatus();
    }

    @SuppressLint("LongLogTag")
    @Override
    public void onRefreshCall() {
        Log.d(TAG, "onRefreshCall");
        restLoadMore();
        mPage = 1;
        isRefreshCall = true;
        loadData();
    }

    @Override
    public void onLoadMoreRequested() {
        if(!isHasNextPage) {
            getAdapter().loadMoreEnd();
            return;
        }
        loadData();
    }

    private void updateFastRideMessage(OrderResponse orderResponse) {
        if (orderResponse.isHasNextPage()) {
            mPage = orderResponse.getNextPage();
            getAdapter().loadMoreComplete();
        } else {
            getAdapter().loadMoreEnd();
        }
    }

    /**
     * @param text
     * @param delay
     * @return
     */
    private Observable<String> createCommonObservable(String text, int delay) {
        return Observable.<String>create(subscriber -> subscriber.onNext(text))
                .delay(delay, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Bundle bundle = new Bundle();
        bundle.putInt(Constant.ORDER_STATUS, getView().getOrderStatus());
        ProxyFragmentActivity.start(getActivity(), OrderDetailFragment.class,bundle);
    }

    @Override
    public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
        return false;
    }

    private void loadData() {
        // 返回为空时，直接返回
        if (getDataByType() == null) return;
        getDataByType()
                .compose(RxSchedulerUtils.<OrderResponse>normalSchedulersTransformer())
                .compose(this.bindUntilEvent(PresentEvent.DESTROY))
                .subscribe(new Subscriber<OrderResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        getViewDelegate().showErrorView("请求出错了！", e.getMessage());
                    }

                    @Override
                    public void onNext(OrderResponse orderResponse) {
                        // 刷新时，列表数据为空时显示emptyview
                        if(isRefreshCall && orderResponse.getList().size() == 0) {
                            refreshComplete();
                            getViewDelegate().showEmptyView();
                            return;
                        }

                        updateFastRideMessage(orderResponse);
                        if (isRefreshCall) {
                            // 刷新时的请求
                            testDataList.clear();
                            testDataList.addAll(orderResponse.getList());
                            publishListData(testDataList);
                            isRefreshCall = false;
                        } else {
                            getAdapter().addData(orderResponse.getList());
                            getAdapter().notifyDataSetChanged();
                        }
                    }
                });
    }

    private Observable<OrderResponse> getDataByType() {
        Observable<OrderResponse> observable = null;
        switch (type) {
            case Constant.ORDER_PENDING:
                observable = ControlSystemRepository.getPendingOrders(mRow, mPage);
                break;
            case Constant.ORDER_PICK_UP:
                observable = ControlSystemRepository.getPickupOrders(mRow, mPage);
                break;
            case Constant.ORDER_DISPATCH:
                observable = ControlSystemRepository.getDistributionOrders(mRow, mPage);
                break;
            case Constant.ORDER_COMPLETED:
                observable = ControlSystemRepository.getFinishedOrders(mRow, mPage, "", "");
                break;
            case Constant.ORDER_CANCEL:
                observable = ControlSystemRepository.getCancelOrders(mRow, mPage, "", "");
                break;
            default:
        }
        return observable;
    }
}
